import UserSession from "@/UserSession";
import Redirect from "umi/redirect";
import { connect } from "dva";
import { getAuthority } from "@/utils/authority";
import pathToRegexp from "path-to-regexp";
import jsonDataUtils from "@/utils/jsonDataUtils";
import getRouteAuthority from "./TestRouteAuthority";

function RouteRedirect({ children, location, routerData }) {
	const activeMenu = UserSession.getActiveMenu();
	const leftMenu = UserSession.getLeftMenu() && jsonDataUtils.isJsonString(UserSession.getLeftMenu()) ? JSON.parse(UserSession.getLeftMenu()) : '';
	const auth = getAuthority() ? getAuthority() : [];

	const getFirstPath = (path, routeData) => {
		let url = "";
		routeData.forEach((route) => {
			// match prefix
			if (route.authority && route.authority.indexOf(auth[0]) > -1) {
				if (route.routes) {
					url = getFirstPath(path, route.routes);
				} else {
					url = route.path;
				}
			} else if (!auth[0]) {
				url = '/home'
			} else if (auth[0] == 'modelPage') {
				url = '/homeType'
			} else if (auth[0] == 'indexPage') {
				url = '/home'
			}
		});
		return url;
	};
	// console.log(location, location.pathname, getFirstPath(location.pathname, routerData), activeMenu);
	// console.log(children, location, routerData);
	let hideMenu = window.localStorage.getItem("hideMenu");
	let routers = [
		'/myKnowledge', '/systemKnowledge',
		'/knowledgeDesign/customDictionary', '/basic/antistopReply', '/knowledgeDesign/customApi/',
		'/capacity/knowledgeSmartMaintenance', '/capacity/medicalKnowledge', '/waitingLearningIssue',
		'/enterprise/robotManagement'
	];

	// 取左侧菜单缓存，若有，则走缓存路由，若没有，则走getFirstPath路由
  // 若有左侧菜单 则判断该路由的权限是否符合当前系统的权限 是则跳转缓存路由 否走getFirstPath路由（用于修复同事打开两个页面 缓存出错 页面重复刷新问题）

	if (leftMenu && leftMenu[activeMenu]) {
    const activeAuthority = window.localStorage.getItem("robot-authority") ? JSON.parse(window.localStorage.getItem("robot-authority")) : []
    const localAuthority = getRouteAuthority(leftMenu[activeMenu],routerData)
    let newA = new Set(activeAuthority);
    let newB = new Set(localAuthority); 
    let intersectionSet = new Set([...newA].filter(x => newB.has(x)));
    let arr = Array.from(intersectionSet);
    
    //缓存路由不符合当前系统的权限 走getFirstPath路由
    if(arr.length == 0){
      return <Redirect to={getFirstPath(location.pathname, routerData)} />;
    }else{
      if (hideMenu && hideMenu === activeMenu) {
        let routeMenu = null;
        routers.forEach(item => {
          if (leftMenu[activeMenu].indexOf(item) > -1) {
            routeMenu = item;
          }
        })
        return <Redirect to={routeMenu ? routeMenu : leftMenu[activeMenu]} />;
      } else {
        return <Redirect to={leftMenu[activeMenu]} />;
      }
    }
    
	} else {
		return <Redirect to={getFirstPath(location.pathname, routerData)} />;
	}
	// if (location.pathname === "/" && activeMenu == "robotCenter") {
	// 	  return <Redirect to={`/robotManagement`} />;
	// } else {
	// 	  return <Redirect to={getFirstPath(location.pathname, routerData)} />;
	// }
}

export default connect(({ menu: menuModel }) => ({
	routerData: menuModel.routerData,
}))(RouteRedirect);
